//
//  YTCitySeletedViewController.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/12.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTCitySeletedViewController.h"
#import "YTCitySeletedViewModel.h"
#import "UIImage+YTExtension.h"
#import "YTCountrySelectViewCell.h"
#import "YTCitySelecteViewCell.h"
#import "YTCountryModel.h"
#import "YTCityModel.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>

@interface YTCitySeletedViewController ()<UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITableView *cityTableView;
@property (weak, nonatomic) IBOutlet UIView *selectedAreaView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *selectedHeight;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
@property (weak, nonatomic) IBOutlet UILabel *selecteTitle;
@property (strong, nonatomic) YTCitySeletedViewModel *viewModel;

@end

@implementation YTCitySeletedViewController

- (void)initialize {
    _viewModel = [[YTCitySeletedViewModel alloc] init];
    _searchBar.delegate = _viewModel;
    _tableView.tableFooterView = [UIView new];
    [_searchBar setBackgroundImage:[UIImage yt_imageWithColor:[UIColor groupTableViewBackgroundColor]]];
    self.navigationItem.title = @"城市选择";
    if (_isSeleteLive) {
        _selecteTitle.text = @"已选生活城市";
    }
}

- (void)bindViewModel {
    
    RAC(_viewModel, isInland) = RACObserve(self, isInland);
    
    @weakify(self);
    [[self rac_signalForSelector:@selector(viewWillAppear:)] subscribeNext:^(id x) {
        @strongify(self);
        [self.viewModel.loadDataCommand execute:nil];
    }];
    
    [[_viewModel.loadDataCommand.executionSignals switchToLatest] subscribeNext:^(RACTuple *tuple) {
        @strongify(self);
        [self.tableView reloadData];
    }];
    
    [_viewModel.loadDataCommand.executing subscribeNext:[self yt_showHudWithTips:nil]];
    
    [_viewModel.searchSignal subscribeNext:^(NSNumber *isSearching) {
        @strongify(self);
        if (!isSearching.boolValue) {
            [self.searchBar resignFirstResponder];
            self.searchBar.text = @"";
        }
        self.cityTableView.hidden = YES;
        [self.tableView reloadData];
    }];
    
    [[[_viewModel.didSelectItemCommand.executionSignals
      switchToLatest]
      deliverOn:[RACScheduler mainThreadScheduler]]
      subscribeNext:^(NSArray<NSString *> *selectedArray) {
          @strongify(self);
          [self addButtonWithIndex:selectedArray.count - 1 title:[selectedArray lastObject]];
          if ((selectedArray.count - 1)%4 == 0) {
              [self updateSelectedArea:selectedArray.count];
          }
          self.navigationItem.rightBarButtonItem.enabled = selectedArray.count > 0;
          [self.cityTableView reloadData];
    }];
    
    _deleteBtn.rac_command = _viewModel.deleteCommand;
    [[_viewModel.deleteCommand.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [self reloadSeletedArea];
        [self.cityTableView reloadData];
        self.navigationItem.rightBarButtonItem.enabled = self.viewModel.selectArray.count > 0;
    }];
    
    [[_viewModel.showCityCommand.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.cityTableView.hidden = NO;
        [self.cityTableView reloadData];
    }];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isSeleteLive && _viewModel.selectArray.count >= 1) return;
    if (!_isSeleteLive && _viewModel.selectArray.count >= 10) return;
    if ([tableView isEqual:_cityTableView]) { // 城市列表
        NSString *title = _viewModel.cityArray[indexPath.row].name;
        if (![_viewModel.selectArray containsObject:title]) {
            [_viewModel.didSelectItemCommand execute:_viewModel.cityArray[indexPath.row]];
        } else {
            [_viewModel.selectArray removeObject:title];
            [_viewModel.deleteCommand execute:nil];
        }
    } else { // 国家
        if (_viewModel.isSearch) { // 如果是搜索也是使用的国家列表展示
            NSString *title = _viewModel.searchArray[indexPath.row].name;
            BOOL containTitle = [_viewModel.selectArray containsObject:title];
            if (!containTitle) [_viewModel.didSelectItemCommand execute:_viewModel.searchArray[indexPath.row]];
            return;
        }
        _viewModel.dataDict[_viewModel.keyArray[indexPath.section]][indexPath.row].isSelected = YES;
        NSString *key = _viewModel.keyArray[indexPath.section];
        NSArray<YTCityModel *> *cityList = _viewModel.dataDict[key][indexPath.row].cityList;
        [_viewModel.showCityCommand execute:cityList];
    }
    // 字体变色
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.detailTextLabel.textColor = [UIColor whiteColor];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.textColor = [UIColor blackColor];
    if ([tableView isEqual:_tableView] && !_viewModel.isSearch) {
        _viewModel.dataDict[_viewModel.keyArray[indexPath.section]][indexPath.row].isSelected = NO;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([tableView isEqual:_cityTableView]) return;
    UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
    headerView.textLabel.textColor = kMainBlueColor;
    headerView.contentView.backgroundColor = [UIColor groupTableViewBackgroundColor];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if ([tableView isEqual:_cityTableView]) return nil;
    return _viewModel.isSearch ? @"结果" : [_viewModel.keyArray[section] uppercaseString];
}

#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_tableView]) {
        YTCountrySelectViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YTSelectCountryCell" forIndexPath:indexPath];
        if (!_viewModel.isSearch) {
            cell.textLabel.text = _viewModel.dataDict[_viewModel.keyArray[indexPath.section]][indexPath.row].name;
            cell.detailTextLabel.text = _viewModel.dataDict[_viewModel.keyArray[indexPath.section]][indexPath.row].nameEn;
            cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"profile_selected_country"]];
        } else {
            cell.textLabel.text = _viewModel.searchArray[indexPath.row].name;
            cell.detailTextLabel.text = _viewModel.searchArray[indexPath.row].nameEn;
            cell.selectedBackgroundView = nil;
        }
        // 只有在非搜索情况下才能去判断是否有选中
        if (!_viewModel.isSearch) {
            if (_viewModel.dataDict[_viewModel.keyArray[indexPath.section]][indexPath.row].isSelected) {
                cell.textLabel.textColor = [UIColor whiteColor];
                cell.detailTextLabel.textColor = [UIColor whiteColor];
            }
        }
        
        return cell;
    }
    
    if ([tableView isEqual:_cityTableView]) {
        YTCitySelecteViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YTSelectCityCell" forIndexPath:indexPath];
        cell.textLabel.text = _viewModel.cityArray[indexPath.row].name;
        cell.detailTextLabel.text = _viewModel.cityArray[indexPath.row].nameEn;
        
        if ([_viewModel.selectArray containsObject:cell.textLabel.text]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        return cell;
    }
    return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _viewModel.isSearch || [tableView isEqual:_cityTableView] ? 1 : _viewModel.keyArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:_cityTableView]) return _viewModel.cityArray.count;
    return _viewModel.isSearch ? _viewModel.searchArray.count : [_viewModel.dataDict objectForKey:_viewModel.keyArray[section]].count;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (_viewModel.isSearch || [tableView isEqual:_cityTableView]) return nil;
    
    NSMutableArray *temp = [NSMutableArray array];
    for (NSString *str in _viewModel.keyArray) {
        [temp addObject:[str uppercaseString]];
    }
    return temp;
}

#pragma mark - DZNEmptyDataSetSource

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"没有找到你搜的城市～";
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0f],
                                 NSForegroundColorAttributeName: kGrayColor};
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"public_noresults"];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -100;
}

#pragma mark - Private

- (void)addButtonWithIndex:(NSInteger)index title:(NSString *)title {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [button setTitleColor:kBlackColor forState:UIControlStateNormal];
    [button setTitleColor:kMainBlueColor forState:UIControlStateSelected];
    [button setBackgroundImage:[UIImage imageNamed:@"public_button_check"] forState:UIControlStateSelected];
    button.layer.cornerRadius = 3.0;
    button.layer.borderWidth = 1.0;
    button.layer.borderColor = kGrayColor.CGColor;
    [button addTarget:self action:@selector(deleteCityAction:) forControlEvents:UIControlEventTouchUpInside];
    [_selectedAreaView addSubview:button];
    CGFloat width = (kScreenWidth-50)/4;
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(width, 35));
        make.left.mas_equalTo(15 + index%4 * (width + 5));
        make.top.mas_equalTo(5 + index/4 * 44);
    }];
}

- (void)deleteCityAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    sender.layer.borderColor = sender.selected ? kMainBlueColor.CGColor : kGrayColor.CGColor;
    if (sender.selected) {
        [_viewModel.deleteArray addObject:sender.titleLabel.text];
    } else {
        [_viewModel.deleteArray removeObject:sender.titleLabel.text];
    }
}

- (void)reloadSeletedArea {
    for (UIView *view in _selectedAreaView.subviews) {
        [view removeFromSuperview];
    }
    
    for (NSInteger i = 0; i < _viewModel.selectArray.count; i++) {
        [self addButtonWithIndex:i title:_viewModel.selectArray[i]];
    }
    
    [self updateSelectedArea:_viewModel.selectArray.count];
}

- (void)updateSelectedArea:(NSInteger)count {
    [_selectedAreaView updateConstraintsIfNeeded];
    _selectedHeight.constant = (count/4 * 44) + 44;
}

- (IBAction)selectedCompleteAction:(UIBarButtonItem *)sender {
    if (!_seletedCallBack) return;
    [_seletedCallBack sendNext:RACTuplePack(_viewModel.selectArray, _viewModel.selectIDArray)];
    [_seletedCallBack sendCompleted];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
